<template>
    <div>
        <el-table :data="roleList" style="width: 100%">
            <el-table-column prop="roleName" label="角色名称" width="180" />
            <el-table-column prop="roleType" label="角色类型" width="180" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="handleEdit(scope.row)" size="small" type="primary" round>编辑</el-button>
                    <el-popconfirm title="确定要删除吗？" confirm-button-text="确定" cancel-button-text="取消"
                        @confirm="handleDelete(scope.row)">
                        <template #reference>
                            <el-button size="small" type="danger" round>删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog v-model="dialogVisible" title="编辑" width="30%">
            <el-form :model="roleForm">
                <el-form-item label="角色名称">
                    <el-input v-model="roleForm.roleName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="权限列表">
                    <!-- :default-checked-keys="roleForm.rights" -->
                    <el-tree ref="treeRef" :data="rightList" show-checkbox default-expand-all node-key="path"
                        :check-strictly="true" highlight-current :props="{
                            children: 'children',
                            label: 'title',
                        }" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleUpdate">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import axios from 'axios'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
const roleList = ref([])    // 角色列表
const rightList = ref([])   // 权限列表
onMounted(async () => {
    await Promise.all([getList(), getRightList()])

    // 调用接口获取角色列表数据
    // getList()

    // 调用接口获取权限列表数据
    // getRightList()
})

const getList = async () => {
    var res = await axios.get('/adminapi/roles')
    roleList.value = res.data
}

const getRightList = async () => {
    var res = await axios.get('/adminapi/rights')
    rightList.value = res.data
}

// 控制对话框显示隐藏
const dialogVisible = ref(false)
const roleForm = reactive({
    roleName: '',
    // rights: []
})

// 保存当前更新的item项的_id
let curItemId

const treeRef = ref(null)

const handleEdit = (row) => {
    roleForm.roleName = row.roleName
    curItemId = row._id
    // 顺序不能调换，因为只有显示对话框以后才会初始化树控件
    dialogVisible.value = true
    nextTick(() => {
        // 只有等待树控件初始化完以后，才能拿到树控件实例，进而调用方法设置默认选中项
        treeRef.value.setCheckedKeys(row.rights)
    })
}

const handleUpdate = () => {
    dialogVisible.value = false
    updateRole()
}

const updateRole = async () => {
    console.log(curItemId)
    console.log(roleForm.roleName)
    console.log(treeRef.value.getCheckedKeys())

    var res = await axios.put(`/adminapi/roles/${curItemId}`, {
        roleName: roleForm.roleName,
        rights: treeRef.value.getCheckedKeys()
    })
    if (res.statusText === 'OK') {
        ElMessage({
            message: '更新成功',
            type: 'success'
        })
        await getList()
        // 如果需要保证管理员更新权限名称后后，就能立即看到左侧菜单栏的变更，可以通过刷新界面这种简单的方式实现
        // location.reload()
    } else {
        ElMessage({
            message: '更新失败',
            type: 'error'
        })
    }
}

const handleDelete = async (row) => {
    axios.delete('/adminapi/roles', {
        data: {
            id: row._id
        }
    })
    // location.reload()
    await getList()
}
</script>